package cn.lzy.demo;

import cn.lzy.consumer.RoleService;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;

/**
 * @Description
 * @Author lzy
 * @Date 2023/12/6 18:07
 * @Version
 **/
public class Demo03OfParent {

    /**
     * 父子容器
     * @param args
     */
    public static void main(String[] args) {
        ClassPathXmlApplicationContext consumerCtx = new ClassPathXmlApplicationContext("consumer.xml");
        ClassPathXmlApplicationContext merchantCtx = new ClassPathXmlApplicationContext("merchant.xml");

        // 设置父容器
        merchantCtx.setParent(consumerCtx);
        merchantCtx.refresh();

        // 获取Bean
        // （当子容器调用 getBean 方法去获取一个 Bean 的时候，如果当前容器没找到，就会去父容器查找，一直往上找，直到找到为止。）
        cn.lzy.consumer.RoleService consumerBean = consumerCtx.getBean(cn.lzy.consumer.RoleService.class);
        cn.lzy.merchant.RoleService merchantBean = merchantCtx.getBean(cn.lzy.merchant.RoleService.class);
        cn.lzy.consumer.RoleService bean3 = merchantCtx.getBean(cn.lzy.consumer.RoleService.class);

        System.out.println("consumerBean = " + consumerBean);
        System.out.println("merchantBean = " + merchantBean);
        System.out.println("bean3 = " + bean3);


        // === 特殊情况 ===
        // getBeanNamesForType——该方法只能在当前容器中查找，并不会去父容器中查找
        String[] names1 = merchantCtx.getBeanNamesForType(cn.lzy.merchant.RoleService.class);
        String[] names2 = merchantCtx.getBeanNamesForType(cn.lzy.consumer.RoleService.class);
        System.out.println("Arrays.toString(names1) = " + Arrays.toString(names1));
        System.out.println("Arrays.toString(names2) = " + Arrays.toString(names2));

        // 若希望能够根据类型查找 Bean 名称，并且还能够自动去父容器中查找，那么可以使用 Spring 给我们提供的工具类-BeanFactoryUtils.beanNamesForTypeIncludingAncestors
        String[] names3 = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(merchantCtx, cn.lzy.consumer.RoleService.class);
        for (String name : names3) {
            System.out.println("name = " + name);
        }
    }
}
